package com.aj.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.util.FloatMath;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.webkit.WebView;

public class UIUtil {

	/**
	 * 将给定图片维持宽高比缩放后，截取正中间的正方形部分。
	 * 
	 * @param bitmap
	 *            原图
	 * @param edgeLength
	 *            希望得到的正方形部分的边长
	 * @return 缩放截取正中部分后的位图。
	 */
	public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength) {
		if (null == bitmap || edgeLength <= 0) {
			return null;
		}

		Bitmap result = bitmap;
		int widthOrg = bitmap.getWidth();
		int heightOrg = bitmap.getHeight();

		if (widthOrg > edgeLength && heightOrg > edgeLength) {
			// 压缩到一个最小长度是edgeLength的bitmap
			int longerEdge = (int) (edgeLength * Math.max(widthOrg, heightOrg) / Math.min(widthOrg, heightOrg));
			int scaledWidth = widthOrg > heightOrg ? longerEdge : edgeLength;
			int scaledHeight = widthOrg > heightOrg ? edgeLength : longerEdge;
			Bitmap scaledBitmap;

			try {
				scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
			} catch (Exception e) {
				return null;
			}

			// 从图中截取正中间的正方形部分。
			int xTopLeft = (scaledWidth - edgeLength) / 2;
			int yTopLeft = (scaledHeight - edgeLength) / 2;

			try {
				result = Bitmap.createBitmap(scaledBitmap, xTopLeft, yTopLeft, edgeLength, edgeLength);
				scaledBitmap.recycle();
			} catch (Exception e) {
				return null;
			}
		}

		return result;
	}

	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		// final float roundPx = 24;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	public static String FormatText(String src) {
		String pStr = src.replaceAll(" ", "");
		String tag = "        " + pStr.replaceAll("\n", "\n        ");
		return tag;
	}

	private final static float round = 10;

	/**
	 * 控件圆角�?
	 * 
	 * @param view
	 *            �?��圆角化的控件
	 * @param corner
	 *            圆角化的角度，数值越大圆角弧度越大，�?时使用默认�?
	 */
	public static void toCorner(View view, float corner) {
		// 如果没有设置角度，则用默认角�?
		float roundPx = corner == 0 ? round : corner;
		GradientDrawable gd = new GradientDrawable();
		gd.setCornerRadii(new float[] { roundPx, roundPx, roundPx, roundPx, roundPx, roundPx, roundPx, roundPx });
		view.setBackgroundDrawable(gd);

	}

	/**
	 * 
	 * 根据指定的图像路径和大小来获取缩略图
	 * 
	 * 此方法有两点好处�?
	 * 
	 * 1. 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度�?
	 * 
	 * 第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图�?
	 * 
	 * 2. 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使
	 * 
	 * 用这个工具生成的图像不会被拉伸�?
	 * 
	 * @param imagePath
	 *            图像的路�?
	 * 
	 * @param width
	 *            指定输出图像的宽�?
	 * 
	 * @param height
	 *            指定输出图像的高�?
	 * 
	 * @return 生成的缩略图
	 */

	public static Bitmap getImageThumbnail(String imagePath, int width, int height) {

		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 获取这个图片的宽和高，注意此处的bitmap为null
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		options.inJustDecodeBounds = false; // 设为 false

		// 计算缩放�?
		int h = options.outHeight;
		int w = options.outWidth;
		int beWidth = w / width;
		int beHeight = h / height;
		int be = 1;
		if (beWidth < beHeight) {
			be = beWidth;
		} else {
			be = beHeight;
		}

		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;

		// 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
		bitmap = BitmapFactory.decodeFile(imagePath, options);

		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	/**
	 * 
	 * 获取视频的缩略图先�?过ThumbnailUtils来创建一个视频的缩略图，然后再利用ThumbnailUtils来生成指定大小的缩略图�?
	 * 如果想要的缩略图的宽和高都小于MICRO_KIND，则类型要使用MICRO_KIND作为kind的�?，这样会节省内存�?
	 * 
	 * @param videoPath视频的路
	 *            �?
	 * 
	 * @param width
	 *            指定输出视频缩略图的宽度
	 * 
	 * @param height
	 *            指定输出视频缩略图的高度�?
	 * 
	 * @param kind
	 *            参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND�?其中，
	 *            MINI_KIND: 512 x 384，MICRO_KIND: 96 x 96
	 * 
	 * @return 指定大小的视频缩略图
	 */

	public static Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
		Bitmap bitmap = null;
		// 获取视频的缩略图
		bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
		System.out.println("w" + bitmap.getWidth());
		System.out.println("h" + bitmap.getHeight());
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	public static ArrayList<String> getVideoData(Context context) {
		Cursor cursor = null;
		int count = 0;
		ArrayList<String> data = new ArrayList<String>();
		Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
		String[] projection = new String[] { MediaStore.Video.Media.DATA };
		try {
			cursor = context.getContentResolver().query(uri, projection, null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);
			if (cursor != null) {
				count = cursor.getCount();
				cursor.moveToFirst();
				for (int i = 0; i < count; i++) {
					String string = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
					data.add(string);
					cursor.moveToNext();
				}
			}
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
		return data;
	}

	public static Bitmap createVideoThumbnail(Context context, Uri uri) {
		Bitmap bitmap = null;
		String className = "android.media.MediaMetadataRetriever";
		Object objectMediaMetadataRetriever = null;
		Method release = null;
		try {
			objectMediaMetadataRetriever = Class.forName(className).newInstance();
			Method setDataSourceMethod = Class.forName(className).getMethod("setDataSource", Context.class, Uri.class);
			setDataSourceMethod.invoke(objectMediaMetadataRetriever, context, uri);
			Method getFrameAtTimeMethod = Class.forName(className).getMethod("getFrameAtTime");
			bitmap = (Bitmap) getFrameAtTimeMethod.invoke(objectMediaMetadataRetriever);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (release != null) {
					release.invoke(objectMediaMetadataRetriever);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return bitmap;
	}

	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int getDisplayWidth(Context mContext) {
		WindowManager w = ((Activity) mContext).getWindowManager();
		Display d = w.getDefaultDisplay();
		int width = d.getWidth();
		return width;
	}

	public static int getBitmapHigh(Context mContext, Bitmap mBitmap, int width) {
		return width * mBitmap.getHeight() / mBitmap.getWidth();
	}

	public static void setScaleVsalue(View view, double size) {
		Class classType;
		Method method = null;
		try {
			classType = WebView.class;
			for (Method item : classType.getDeclaredMethods()) {
				if (item.getName().equals("setNewZoomScale")) {
					method = item;
				}
			}
			if (method != null) {
				method.setAccessible(true);
				method.invoke(view, new Object[] { (float) (size / 100.0), true, true });
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取和保存当前屏幕的截图
	 */
	/*
	public static String GetandSaveCurrentImage(Activity mActivity, String rootPath) {
		// 构建Bitmap
		WindowManager windowManager = mActivity.getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		int w = display.getWidth();
		int h = display.getHeight();
		Bitmap Bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
		// 获取屏幕
		View decorview = mActivity.getWindow().getDecorView();
		decorview.setDrawingCacheEnabled(true);
		Bmp = decorview.getDrawingCache();
		// 图片存储路径
		String SavePath = rootPath;
		// 保存Bitmap
		try {
			File path = new File(SavePath);
			// 文件
			String filepath = SavePath + System.currentTimeMillis() + ".png";
			File file = new File(filepath);
			if (!path.exists()) {
				path.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream fos = null;
			fos = new FileOutputStream(file);
			if (null != fos) {
				Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
				fos.flush();
				fos.close();
				return SavePath;
				//Toast.makeText(mContext, "截屏文件已保存至SDCard/ScreenImages/目录下", Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
*/
	/**
	 * 获取SDCard的目录路径功能
	 * 
	 * @return
	 */
	/*
	private String getSDCardPath() {
		File sdcardDir = null;
		// 判断SDCard是否存在
		boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
		if (sdcardExist) {
			sdcardDir = Environment.getExternalStorageDirectory();
		}
		return sdcardDir.toString();
	}
	*/
}
